/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.system.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.system.domain.DictData;
import com.koron.system.service.api.DictDataService;
import com.koron.system.utils.BusinessCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

@Api(tags = "dictData", description = "字典数据相关接口类")
@RestController
@RequestMapping("/dictData")
public class DictDataController {

    @Autowired
    private DictDataService dataService;


    @ApiOperation("保存字典数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id主键,新增时不传，修改时必传" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dictLabel", value = "字典数据标签", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dictKey", value = "字典类型key", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dictValue", value = "字典数据值" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dictIndex", value = "字典数据排序值", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "referenceCount", value = "引用次数" , dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注" , dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String id, @RequestParam(required = true) final String dictLabel,
                                     @RequestParam(required = false) final String dictValue, @RequestParam(required = true) final String dictKey,
                                     @RequestParam(required = false) final String remark, @RequestParam(required = false) final Integer dictIndex,
                                     @RequestParam(required = false) final Long referenceCount) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<Integer> msg = new MessageBean<>();
        if (StringUtils.isEmpty(dictLabel)) {
            msg.setCode(BusinessCode.DICTDATA_EMPTY_LABEL.getCode());
            msg.setDescription(BusinessCode.DICTDATA_EMPTY_LABEL.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(dictKey)) {
            msg.setCode(BusinessCode.DICTDATA_EMPTY_TYPEKEY.getCode());
            msg.setDescription(BusinessCode.DICTDATA_EMPTY_TYPEKEY.getDescription());
            return msg;
        }
        DictData dictData = new DictData();
        Date date = new Date();
        dictData.setUpdateTime(date);
        dictData.setUpdateUser(user == null ? null : user.getName());
        dictData.setId(id);
        dictData.setDictIndex(dictIndex);
        dictData.setDictKey(dictKey);
        dictData.setDictLabel(dictLabel);
        dictData.setDictValue(dictValue);
        dictData.setRemark(remark);
        dictData.setReferenceCount(referenceCount);
        msg = dataService.save(dictData);
        return msg;
    }


    @ApiOperation("批量修改字典数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictDatas", value = "字典数据修改的数据，json字符串，如：[{\"id\": \"1153195857940602880\",\"dictIndex\": \"11\",\"dictLabel\": " +
                    "\"测试字典数据\",\"dictValue\": \"11\",\"dictKey\": \"ceshi01\",\"remark\":\"c测试数据，请勿当真\",\"referenceCount\":0}]", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/batchUpdate.htm", method = RequestMethod.POST)
    public MessageBean<Integer> batchUpdate(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String dictDatas) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<Integer> msg = new MessageBean<>();
        if (StringUtils.isEmpty(dictDatas)) {
            msg.setCode(BusinessCode.DICTDATA_EMPTY_UPDATE_DATA.getCode());
            msg.setDescription(BusinessCode.DICTDATA_EMPTY_UPDATE_DATA.getDescription());
            return msg;
        }
        List<DictData> dictDataList = new ArrayList<>();
        JSONArray array = JSON.parseArray(dictDatas);
        StringBuilder descriptions = new StringBuilder();
        if (null != array && !array.isEmpty()) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject json = (JSONObject) it.next();
                String id = json.getString("id");
                String dictLabel = json.getString("dictLabel");
                String dictKey = json.getString("dictKey");
                String dictValue = json.getString("dictValue");
                Integer dictIndex = json.getInteger("dictIndex");
                Long referenceCount = json.getLong("referenceCount");
                String remark = json.getString("remark");
                if (StringUtils.isEmpty(id)) {
                    descriptions.append(dictLabel).append("-").append(dictKey).append(",");
                } else {
                    DictData dictData = new DictData();
                    Date date = new Date();
                    dictData.setUpdateTime(date);
                    dictData.setUpdateUser(user == null ? null : user.getName());
                    dictData.setId(id);
                    dictData.setDictIndex(dictIndex);
                    dictData.setDictKey(dictKey);
                    dictData.setDictLabel(dictLabel);
                    dictData.setDictValue(dictValue);
                    dictData.setRemark(remark);
                    dictData.setReferenceCount(referenceCount);
                    dictDataList.add(dictData);
                }
            }
        }
        if (dictDataList.size() > 0) {
            msg = dataService.batchUpdate(dictDataList);
            if (StringUtils.isNotEmpty(descriptions.toString())) {
                msg.setDescription("批量修改成功，但由于这些字典数据标签-字典类型key:" + descriptions.toString() + "的id没有传值，对这些数据没有进行处理");
            }
            return msg;
        } else {
            msg.setCode(BusinessCode.DICTDATA_EMPTY_UPDATE_DATA.getCode());
            msg.setDescription(BusinessCode.DICTDATA_EMPTY_UPDATE_DATA.getDescription());
            return msg;
        }
    }


    @ApiOperation("批量删除字典数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "字典数据id,多个之间用,分开", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/batchDelete.htm", method = RequestMethod.POST)
    public MessageBean<Integer> batchDelete(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String ids) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<Integer> msg = new MessageBean<>();
        if (StringUtils.isEmpty(ids)) {
            msg.setCode(BusinessCode.DICTDATA_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.DICTDATA_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        String[] idArray = ids.split("[,，]");
        msg = dataService.batchDelete(Arrays.asList(idArray));
        return msg;
    }


    @ApiOperation("根据主键id获取字典数据详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "字典数据id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.POST)
    public MessageBean<DictData> details(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String id) {
        if (null == user) {
            MessageBean<DictData> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<DictData> msg = new MessageBean<>();
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.DICTDATA_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.DICTDATA_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        msg = dataService.queryOne(id);
        return msg;
    }


    @ApiOperation("获取字典数据列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictLabel", value = "字典数据标签" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dictKey", value = "字典类型key" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数" , dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<DictData>> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String dictLabel, @RequestParam(required = false) final String dictKey,
                                                @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize) {
        if (null == user) {
            MessageBean<DataBean<DictData>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<DataBean<DictData>> msg = new MessageBean<>();
        Integer start = null;
        if (page != null) {
            if (page <= 0) {
                page = 1;
            }
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
        }
        msg = dataService.queryAll(dictLabel, dictKey, start, pageSize);
        msg.getData().setPageNo((page == null || page == 0) ? 1 : page);
        msg.getData().setPageSize((pageSize == null || pageSize == 0) ? 10 : pageSize);
        return msg;
    }

}
